home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c
- Subject: Re: gets() question
- Date: Sun, 07 Jan 1996 16:54:10 GMT
- Organization: Netcom
- Message-ID: <30eff9c3.137769152@nntp.ix.netcom.com>
- References: <4cosgf$rir@newsbf02.news.aol.com>
- NNTP-Posting-Host: ix-dc7-25.ix.netcom.com
- X-NETCOM-Date: Sun Jan 07 8:53:58 AM PST 1996
- X-Newsreader: Forte Agent .99c/16.141
-
- simpsondg@aol.com (SimpsonDG) wrote:
-
- |>Can any of you C gurus out there help me with this? I have a
- problem with
- |>gets() that I don't understand. The program below will successfully
- input
- |>the string s[0], but will simply ignore the gets() that inputs s[1]
- and
- |>goes on to ask for i[1]. What's the deal? A little experimenting
- seems
- |>to indicate that the problem arises when I have a gets() following a
- |>scanf() -- e.g., a program using only gets() or only scanf() works
- fine.
- |>
- |>David Simpson
- |>
- |>--------------------------------------------------------------------------
- |>-------------------
- |>
- |>#include "stdio.h"
- |>
- |>void main(void)
- |>{
- |> int i[5];
- |> char s[3][10];
- |>
- |> printf ("Enter s[0]: ");
- |> gets (s[0]);
- |>
- |> printf ("Enter i[0]]: ");
- |> scanf ("%d",&i[0]);
- |>
- |> printf ("Enter s[1]: ");
- |> gets (s[1]); /* this gets() doesn't wait for
- input */
- |>
- |> printf ("Enter i[1]]: ");
- |> scanf ("%d",&i[1]);
- |>}
-
- scanf() reads characters that match the format item. When it hits one
- that doesn't fit, it pushes it back on the input and continues. Here
- you are entering an integer followed by a newline. The newline gets
- pushed back, so the first think the next gets() sees is the end of the
- line. Since no more input is required, it returns immediately.
-
- Note also that it's a very good idea not to use gets() since there is
- no protection against overrunning the array. fgets() is much safer.
-
- The easiest way to handle this problem is to use fgets() to read each
- line and then use sscanf() or some other function to get numeric data.
-
-
- Michael M Rubenstein
-